<!--
 * @Descripttion:挂账回款首页
-->
<template>
  <div>
    <div class="onAccount-content-wrap">
      <!-- 左边盒子 -->
      <div class="left-box" :class="{ fullWidth: selectedOrderId ? false : true }">
        <div class="left-box-title">挂账回款</div>
        <!-- 头部搜索栏 -->
        <div class="search-box-wrap">
          <!-- 支付方式 -->
          <div class="payMethod-box">
            <el-select
              v-model="pageListQuery.status"
              clearable
              class="select"
              style="width: 180px"
              placeholder="请选择回款状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <!-- 查询时间 -->
          <div class="payMethod-box">
            <el-date-picker
              class="date-picker"
              v-model="pageListQuery.betweenTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </div>
          <!-- 支付方式 -->
          <div class="payMethod-box">
            <el-select
              v-model="pageListQuery.payMethod"
              clearable
              style="width: 180px"
              class="select"
              placeholder="请选择支付方式"
            >
              <el-option
                v-for="item in payMethodList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <!-- 输入框 -->
          <div class="search-input-box">
            <img class="search-icon" src="@/assets/images/home/search-icon.png" alt="" />
            <input
              class="input"
              type="text"
              placeholder="请输入搜索关键词"
              v-model.trim="pageListQuery.search"
              @input="onSearch"
              clearable
            />
          </div>
          <span class="search-btn" @click="onSearch">查询</span>
        </div>
        <!-- 营业账单列表相关组件 -->
        <div class="table-wrap" :class="{ fullWidth: selectedOrderId ? false : true }">
          <onAccountTableList
            :table-data="tableData"
            :loading="tableLoading"
            @onSelectOrderId="onSelectOrderId"
          />
        </div>
        <div class="table-total">
          <span>共{{ pageListTotal }}条</span>
          <div>
            <Pagination
              v-show="pageListTotal > 0"
              :total="pageListTotal"
              v-model:page="pageListQuery.page"
              v-model:limit="pageListQuery.limit"
              @pagination="getCreditLogList"
              :pageSizes="[15, 45, 75, 100]"
            />
          </div>
        </div>
        <!-- 底部数据汇总&&按钮组 -->
        <div class="data-summary-box">
          <span></span>
          <div class="sumary-btn-group">
            <span class="return" @click="handleAction('return')">回款</span>
            <span class="CounterReturn" @click="handleAction('counterReturn')">反回款</span>
            <span class="cancel" @click="handleAction('cancel')">返回</span>
          </div>
        </div>
      </div>
      <!-- 右边盒子 -->
      <div class="right-box" v-show="showRightPanel">
        <OnAccountCard
          :selectedOrderId="selectedOrderId"
          @getOrderCreditDetail="getOrderCreditDetail"
        />
      </div>
    </div>
    <!-- 新增回款弹窗组件 -->
    <Return
      v-model:returnVisible="onAccountData.isShowReturn"
      :selectedLogId="selectedLogId"
      :selectedTableRowOrderData="selectedTableRowOrderData"
      @onConfirmSuccess="onSearch"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import OnAccountCard from './components/OnAccountCard/Index.vue'
import onAccountTableList from './components/onAccountTableList/Index.vue'
import Return from './components/Return/Index.vue'
import Pagination from '@/components/Pagination/Index.vue'
import { creditLogList, logPayCancel } from '@/api/statistics'
import { dealAssignDataFunction, debounce } from '@/utils/toolsValidate'
import messageTips from '@/components/messageTips/index'

const route = useRoute()
const router = useRouter()

// 表格数据
const tableData = ref<any[]>([])
// 控制右侧面板显示状态
const showRightPanel = ref(false)
// 表格加载状态
const tableLoading = ref(false)

// 弹窗数据
const onAccountData = ref({
  isShowReturn: false
})

// 分页相关参数
const pageListQuery = ref({
  page: 1,
  limit: 15,
  // 回款状态(-1:全部 0:未回款 1:已回款 2:回款中)
  status: -1,
  // 搜索收银人/回款人/账户名称
  search: '',
  // 账户id
  org_id: null,
  // 时间范围
  betweenTime: [],
  // 支付方式
  payMethod: null
})

// 分页列表总条数
const pageListTotal = ref(0)
// 选中当前表格当行的订单id
const selectedOrderId = ref('')
// 选中当前表格当行的记录id
const selectedLogId = ref('')
// 选中当前表格当行的对象row数据
const selectedTableRowOrderData = ref({})

// 回款状态列表
const statusList = [
  { label: '全部', value: -1 },
  { label: '未回款', value: 0 },
  { label: '已回款', value: 1 },
  { label: '回款中', value: 2 }
]

// 支付方式列表
// 支付方式(wechat:微信支付 alipay:支付宝 balance:余额 cash:现金 on_account:挂账 virtual:其他)
const payMethodList = [
  { label: '微信支付', value: 'wechat' },
  { label: '支付宝', value: 'alipay' },
  { label: '余额', value: 'balance' },
  { label: '现金', value: 'cash' },
  { label: '挂账', value: 'on_account' },
  { label: '其他', value: 'virtual' }
]

// 搜索挂账订单列表
const onSearch = debounce(() => {
  pageListQuery.value.page = 1
  getCreditLogList()
}, 500)

// 获取挂账订单列表
const getCreditLogList = async () => {
  try {
    tableLoading.value = true
    const res = await creditLogList(pageListQuery.value)
    if (res.status === 200) {
      tableData.value = dealAssignDataFunction([], res?.data?.list?.data)
      pageListTotal.value = dealAssignDataFunction(0, res?.data?.list?.total)
    }
  } catch (error) {
    console.error('获取挂账订单列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

//获取订单挂账详情
const getOrderCreditDetail = (datas: any) => {
  if (!datas) {
    selectedOrderId.value = ''
  }
}

// 选择当前表格当行的订单相关数据
const onSelectOrderId = (datas: any) => {
  // 订单id
  selectedOrderId.value = datas.order_id
  // 记录id
  selectedLogId.value = datas.log_id
  selectedTableRowOrderData.value = datas
  // 第一次点击时显示右侧面板，之后不再隐藏
  if (!showRightPanel.value) {
    showRightPanel.value = true
  }
}

// 操作按钮处理
const handleAction = (action: string) => {
  switch (action) {
    case 'return':
      if (!selectedLogId.value) {
        ElMessage.warning('请先选择回款订单')
        return
      }
      onAccountData.value.isShowReturn = true
      break
    case 'counterReturn':
      if (!selectedLogId.value) {
        ElMessage.warning('请先选择回款订单')
        return
      }
      if (selectedTableRowOrderData.value.repayment_status !== 1) {
        ElMessage.warning('已回款订单才能执行此操作')
        return
      }
      handleCounterReturn()
      break
    case 'cancel':
      router.go(-1)
      break
    default:
      break
  }
}

// 反回款处理
const handleCounterReturn = async () => {
  try {
    const messageInstance = await messageTips.message(
      {
        title: '反回款',
        content: '确定要执行反回款操作吗？\n此操作将撤销已完成的回款记录。',
        isOnCancel: true,
        onCancelText: '取消',
        onSumbitText: '确认'
      },
      async () => {
        // 确认后的处理逻辑
        try {
          messageInstance.setLoading(true)

          // 调用反回款API
          await logPayCancel({
            log_id: selectedLogId.value
            // 其他必要参数
          })

          ElMessage.success('反回款操作成功')
          onSearch() // 刷新列表
        } catch (error) {
          console.error('反回款操作失败:', error)
          ElMessage.error('反回款操作失败')
        } finally {
          messageInstance.setLoading(false)
        }
      }
    )
  } catch (error) {
    // 用户取消操作
    console.log('用户取消反回款操作')
  }
}

// 初始化
onMounted(() => {
  pageListQuery.value.org_id = route.query.org_id
  // 获取挂账订单列表
  getCreditLogList()
})
</script>

<style scoped lang="scss">
::v-deep {
  .el-input__inner {
    border-radius: 12px;
  }
}

.fullWidth {
  width: 1600px !important;
  transition: all 1s !important;
}

.onAccount-content-wrap {
  display: flex;
  align-items: flex-start;

  .left-box {
    box-sizing: border-box;
    width: 1284px;
    min-height: 986px;
    background: #ffffff;
    border-radius: 20px;
    box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);
    display: flex;
    align-items: flex-start;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: 20px;
    transition: all 1s !important;

    .left-box-title {
      width: 100%;
      padding: 30px 0;
      background: #f4f4f4;
      border-radius: 20px 20px 0px 0px;
      font-size: 20px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      color: #333333;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .search-box-wrap {
      width: 100%;
      padding: 20px 30px;
      height: 88px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      gap: 20px;

      .betweenTime-box {
        .betweenTime-text {
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          margin-left: 20px;
          margin: 20px;
        }
      }

      .payMethod-box {
        display: flex;
        align-items: center;

        .payMethod-text {
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          text-align: left;
          color: #333333;
          margin-right: 13px;
        }
      }

      .search-input-box {
        width: 260px;
        height: 40px;
        border: 1px solid #d2d2d2;
        border-radius: 25px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        padding-left: 20px;
        margin-left: 20px;

        .search-icon {
          flex-shrink: 0;
          width: 14px;
          height: 14px;
        }

        .input {
          border: none;
          outline: none;
          width: 190px;
          font-size: 12px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333;
          margin-left: 10px;
        }

        > .input::-webkit-input-placeholder {
          font-size: 12px;
          line-height: 30px;
        }
      }
    }

    .table-wrap {
      width: 1284px;
      padding: 0 20px;
      border-radius: 0px 0px 0px 20px;
      box-sizing: border-box;
      transition: all 1s;
    }

    .table-total {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
      padding: 0 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;
      width: 100%;
      box-sizing: border-box;
    }

    .data-summary-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      align-items: center;
      margin-top: 20px;
      padding-left: 30px;
      padding-right: 30px;

      .summary-text {
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #30314a;
      }

      .sumary-btn-group {
        display: flex;
        justify-content: space-around;
        align-items: center;

        .return {
          width: 120px;
          height: 52px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          margin-left: 40px;
        }

        .CounterReturn {
          width: 138px;
          height: 52px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-left: 40px;
          cursor: pointer;
        }

        .cancel {
          width: 120px;
          height: 52px;
          margin-left: 40px;
          cursor: pointer;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }

  .right-box {
    margin-left: 30px;
    transition: all 1s;
  }
}

.search-btn {
  width: 96px;
  height: 40px;
  background: #7c0a03;
  border-radius: 12px;
  font-size: 18px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin-left: 30px;
}
</style>
